#include "GASU.h"
#include "Log/Logger.h"
#include "Fanuc/FanucDefine.h"

GASU::GASU(/* args */) : pModBusObj(nullptr)
{
}

GASU::~GASU()
{
    stop();
}

void GASU::init()
{
    // 读配置，暂时不写
    
    // 初始化日志
    Logger::getInstance("log", Logger::DEBUG);
}

void GASU::start()
{
    startModbus();
    startFanuc();
}

void GASU::startModbus()
{
    if (pModBusObj)
        return;
    //pModBusObj = new ModBusCollectManager();
    pModBusObj = std::unique_ptr<ModBusCollectManager>(new ModBusCollectManager());

    modbusConnectInfo info;
    info.strDevice = "/dev/ttyUSB0";
    info.nBaudRate = 19200;
    info.cParity = 'N';
    info.nDataBit = 8;
    info.nStopBit = 1;

    pModBusObj->init(info);
    // std::thread t = std::thread(&ModBusCollectManager::start, pModBusObj);
    // t.detach();
    // vec_Threads.push_back(t); //thread不拷贝，不能直接将thread存入vector
    vec_Threads.push_back(std::thread(&ModBusCollectManager::start, pModBusObj.get()));
}

void GASU::startFanuc()
{
    if (pModBusObj)
        return;
    pFanucObj = std::unique_ptr<FanucCollectManager>(new FanucCollectManager());

    FANUC::fanucConnectInfo info;
    info.strIp = "192.168.2.2";
    info.nPort = 22;
    pFanucObj->init(info);
    vec_Threads.push_back(std::thread(&FanucCollectManager::start, pFanucObj.get()));
}

void GASU::stop()
{
    if (pModBusObj.get())
    {
        pModBusObj->stop();
    }
    if (pFanucObj.get())
    {
        pFanucObj->stop();
    }
    for (int i = 0; i < vec_Threads.size(); i++)
    {
        if (vec_Threads[i].joinable())
        {
            vec_Threads[i].join();
        }
    }
    vec_Threads.clear();
}
